<?php

namespace MoChat\App\Client\Action\Dashboard\Tag;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\DbConnection\Db;
use MoChat\App\Client\Contract\ClientTagContract;
use MoChat\App\Client\Contract\ClientTagGroupContract;
use MoChat\App\Client\Contract\ClientTagPivotContract;
use MoChat\App\WorkContact\Contract\WorkContactTagPivotContract;
use MoChat\App\WorkContact\QueueService\TagGroup\DeleteApply;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\Framework\Request\ValidateSceneTrait;

/**
 * 删除标签组
 * @Controller
 */
class Destory extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var ClientTagPivotContract
     */
    private $clientTagPivotContractService;

    /**
     * @Inject
     * @var ClientTagGroupContract
     */
    protected $clientTagGroupService;

    /**
     * @Inject
     * @var ClientTagContract
     */
    protected $clientTagService;

    /**
     * @Inject
     * @var StdoutLoggerInterface
     */
    protected $logger;

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class),
     * })
     * @RequestMapping(path="/dashboard/clientTag/delete", methods="DELETE")
     */
    public function handle()
    {
        // 接收参数
        $params['groupId'] = $this->request->input('id');
        // 验证参数
        $this->validated($params);
        $groupInfo = $this->clientTagGroupService->getWorkContactTagGroupById((int)$params['groupId']);
        if ($groupInfo['is_default']){
            Db::commit();
            throw new CommonException(ErrorCode::SERVER_ERROR, '默认标签不能修改');
        }
        // 开启事务
        Db::beginTransaction();

        try {
            // 软删除分组
            $res = $this->clientTagGroupService
                ->deleteWorkContactTagGroup((int)$params['groupId']);

            if (!is_int($res)) {
                throw new CommonException(ErrorCode::SERVER_ERROR, '客户标签分组删除失败');
            }

            // 查询该分组下的标签
            $tags = $this->clientTagService->getWorkContactTagsByGroupIds([$params['groupId']], ['id']);

            if (!empty($tags)) {
                $tagIds = array_column($tags, 'id');
                // 删除标签
                $tagDelete = $this->clientTagService
                    ->deleteWorkContactTags($tagIds);

                if (!is_int($tagDelete)) {
                    throw new CommonException(ErrorCode::SERVER_ERROR, '标签删除失败');
                }

                // 删除客户标签
                $contactTag = $this->clientTagPivotContractService->deleteWorkContactTagPivotsByTagId($tagIds);
                if (!is_int($contactTag)) {
                    throw new CommonException(ErrorCode::SERVER_ERROR, '客户标签删除失败');
                }
            }

            Db::commit();
        } catch (\Throwable $e) {
            Db::rollBack();
            throw new CommonException(ErrorCode::SERVER_ERROR, '删除失败');
        }
    }

    /**
     * @return string[] 规则
     */
    public function rules(): array
    {
        return [
            'groupId' => 'required|int',
        ];
    }

    /**
     * 获取已定义验证规则的错误消息.
     */
    public function messages(): array
    {
        return [
            'groupId.required' => '分组id必传',
        ];
    }
}